package com.datastructure.test.mindifferenceinbinarytree;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MinDifferenceInBinaryTree {

    public static void main(String[] args) {

    }

    public int minDifference (TreeNode root) {
        // write code here
        int min = Integer.MAX_VALUE;
        ArrayList<Integer> data = new ArrayList<>();
        inOrder(data,root);
        List<Integer> collect = data.stream().sorted().collect(Collectors.toList());
        for (int i = collect.size()-1; i > 0; i--) {
            min=Math.min(min,collect.get(i)-collect.get(i-1));
        }
        return min;
    }

    private void inOrder(ArrayList<Integer> data, TreeNode root) {
        if(root==null){
            return;
        }
        if(root.left!=null){
            inOrder(data,root.left);
        }
        data.add(root.val);
        if(root.right!=null){
            inOrder(data,root.right);
        }
    }
}

class TreeNode {
   int val = 0;
   TreeNode left = null;
   TreeNode right = null;
   public TreeNode(int val) {
     this.val = val;
   }
 }
